
import { useState, useEffect } from 'react';
import styles from './style.less';
import { TeamOutlined, MenuOutlined, LineChartOutlined,DragOutlined ,EditOutlined} from '@ant-design/icons';
import ProjectIcon from '@/components/projectIcon';
import Lane from '@/components/Scrum/Lane';
import Block from '@/components/Scrum/Block';
import Task from '@/components/Scrum/Task';

import { connect } from 'umi';
import { DragDropContext, Droppable, Draggable } from 'react-beautiful-dnd';
import { isBuffer } from 'lodash';


const Scrum = (props) => {
    const {
        scrumData = {},
        dispatch,

    } = props;

    const blockDragProvided = useState([])
    const [isBlockDraging, setBlockDraging] = useState(false)

    useEffect(() => {
        console.log('---111--')
        if (dispatch) {
            dispatch({
                type: 'scrum/queryScurm',
                payload: 1
            });
        }
    }, []);

    const onDragBeforeStart = (ev) => {

        console.log('onDragBeforeStart', ev)

    }
    const onDragStart = (ev) => {

        if (ev.type.indexOf("lane_") > -1) {
            console.log('onDragUpdate', ev)
            setBlockDraging(true)
        }

    }
    const onDragUpdate = (ev) => {
        if (ev.type.indexOf("lane_") > -1) {
            console.log('onDragUpdate', ev)

        }
    }


    const reorder = (list, startIndex, endIndex) => {
        let result = [...list];
        let [removed] = result.splice(startIndex, 1);
        result.splice(endIndex, 0, removed);
        return {
            dragTask: removed,
            reorderTaskList: result
        };
    };

    const move = (source, destination, droppableSource, droppableDestination) => {
        const sourceClone = Array.from(source);
        const destClone = Array.from(destination);
        const [removed] = sourceClone.splice(droppableSource.index, 1);

        destClone.splice(droppableDestination.index, 0, removed);
        return {
            dragTask: removed,
            sourceTaskList: sourceClone,
            targetTaskList: destClone
        };
    };

    const getList = (droppableId) => {
        let ids = droppableId.split("_")
        let laneLength = scrumData.laneList.length;
        for (let i = 0; i < laneLength; i++) {
            if (ids[0] == scrumData.laneList[i].id) {
                let blockLength = scrumData.laneList[i].blockList.length;
                for (let k = 0; k < blockLength; k++) {
                    if (ids[1] == scrumData.laneList[i].blockList[k].id) {
                        console.log("return", scrumData.laneList[i].blockList[k])
                        return scrumData.laneList[i].blockList[k].taskList;
                    }
                }
            }
        }
        return [];
    }

    const onTaskDragEnd = ({ source, destination }) => {
        if (source.droppableId === destination.droppableId) {
            const reorderDate = reorder(
                getList(source.droppableId),
                source.index,
                destination.index
            );
            let ids = source.droppableId.split("_")
            if (dispatch) {
                dispatch({
                    type: 'scrum/reorder',
                    payload: {
                        ...reorderDate,
                        laneId: ids[0],
                        blockId: ids[1],
                    }
                });
            }

        } else {
            const moveResult = move(
                getList(source.droppableId),
                getList(destination.droppableId),
                source,
                destination
            );
            let ids = source.droppableId.split("_")
            let targetIds = destination.droppableId.split("_")
            if (dispatch) {
                dispatch({
                    type: 'scrum/move',
                    payload: {
                        ...moveResult,
                        blockId: ids[1],
                        laneId: ids[0],
                        targetBlockId: targetIds[1],
                        targetBlaneId: targetIds[0],
                    }
                });
            }
        }
    }

    const onBlockDragEnd = ({ source, destination }) => {
        if (dispatch) {
            dispatch({
                type: 'scrum/blockReorder',
                payload: {
                    sourceBlockIndex: source.index,
                    targetBlockIndex:destination.index
                }
            });
        }
    }

    const onDragEnd = result => {
        const { source, destination } = result;
        console.log(result);
        // dropped outside the list
        if (!destination) {
            return;
        }
        if (result.type == "task") {
            onTaskDragEnd(result)
        } else {
            setBlockDraging(false);
            onBlockDragEnd(result);
        }
    };

    const blockRender = (laneData, block, blockIndex) => {
        return <Droppable
            droppableId={`${laneData.id}_${block.id}`}
            type="task"
            key={`${laneData.id}_${block.id}`}>
            {(provided, snapshot) => {
                return (
                    <Block key={block.id}
                        provided={provided}
                        snapshot={snapshot}
                        taskCnt={block.taskList ? block.taskList.length : 0}>
                        {block.taskList ? (block.taskList.map((task, index) => {
                            return <Draggable
                                key={task.id}
                                type="task"
                                draggableId={`${task.id}`}
                                index={index}>
                                {(provided, snapshot) => (
                                    <Task
                                        provided={provided}
                                        task={task}>
                                    </Task>
                                )}
                            </Draggable>
                        })) : ''}
                        {provided.placeholder}
                    </Block>
                )
            }}
        </Droppable>
    }
    const blockDragingStyle = (blockIndex) => (<div>
        {scrumData.laneList.map((lane,index) => {
            
            let block = lane.blockList[blockIndex];
            return index > 0 && (<div key={block.id} style={{
                marginTop:20
            }}>
                <Block>
                    {block.taskList ? (block.taskList.map((task, index) => {
                        return <Task
                            key={task.id}
                            task={task}>
                        </Task>
                    })) : ''}
                </Block>
            </div>)
        })}
    </div>)

   
    const laneListRender = (laneData, index) => (
        laneData ? laneData.blockList.map((block, blockIndex) => {
            if (index == 0) {
                return (
                    <Draggable key={block.id}
                        draggableId={`${index}-${block.id}`}
                        type={"block_" + index}
                        index={blockIndex}>
                        {(provided, snapshot) => {
                            return (
                                <div ref={provided.innerRef}
                                    {...provided.draggableProps}
                                >
                                    <div className={styles.blockHeader}
                                        {...provided.dragHandleProps}
                                    >
                                        <div>{block.name ? block.name : '未命名'}   <EditOutlined style={{}}></EditOutlined></div>
                                        <DragOutlined style={{fontSize:20}}></DragOutlined>
                                    </div>
                                    {blockRender(laneData, block, blockIndex)}
                                    { isBlockDraging ? (blockDragingStyle(blockIndex)) : ''}
                                </div>
                            )
                        }}

                    </Draggable>
                )
            } else {
                return (
                    <div key={block.id}>
                        {blockRender(laneData, block, blockIndex)}
                    </div>
                );
            }
        }) : ''
    )


    return (<div className={styles.container}>
        <div className={styles.header}>
            <div className={styles.title} >{scrumData.name}</div>
            <div className={styles.operate}>
                <div className={styles.operateItem}>{scrumData.startDate} ~ {scrumData.endDate}</div>
                <div className={styles.operateItem}><LineChartOutlined />燃尽图</div>
                <div className={styles.operateItem}><ProjectIcon type={'icon-shoucang'} />收藏</div>
                <div className={styles.operateItem}><TeamOutlined />成员</div>
                <div className={styles.operateItem}><MenuOutlined />操作</div>
            </div>
        </div>
        <div className={styles.laneContainer}>
            <DragDropContext onDragEnd={onDragEnd}
                onDragBeforeStart={onDragBeforeStart}
                onDragStart={onDragStart}
                onDragUpdate={onDragUpdate}>
                {scrumData.laneList ? (scrumData.laneList.map((laneData, index) => {

                    if (index == 0) {
                        return (<Droppable
                            droppableId={`${laneData.id}`}
                            key={`${laneData.id}`}
                            type={"lane_" + index}
                            direction="horizontal">
                            {(provided, snapshot) => {
                                return <Lane key={laneData.id} provided={provided} index={index} laneData={laneData} laneListRender={laneListRender}></Lane>
                            }}

                        </Droppable>
                        )
                    } else if (!isBlockDraging) {
                        return <Lane key={laneData.id} index={index} laneData={laneData} laneListRender={laneListRender}></Lane>
                    }

                })) : ''}
            </DragDropContext>
        </div>
    </div>);
}

const mapStateToProps = ({ scrum, loading }) => {
    let scrumData = scrum.scrumData;
    if (scrumData.blockList) {
        let laneCnt = scrumData.blockList[0].laneList.length;
        let blockLenght = scrumData.blockList.length;
        for (let i = 0; i < laneCnt; i++) {
            let thisLaneMaxCnt = 0;
            for (let k = 0; k < blockLenght; k++) {
                if (scrumData.blockList[k].laneList[i].taskList.length > thisLaneMaxCnt) {
                    thisLaneMaxCnt = scrumData.blockList[k].laneList[i].taskList.length;
                }
            }
            for (let j = 0; j < blockLenght; j++) {
                scrumData.blockList[j].laneList[i].maxLaneTaskCnt = thisLaneMaxCnt;
            }
        }
    }
    return {
        scrumData: scrumData,
        loading: loading.models.scrum,
    }
}


export default connect(mapStateToProps)(Scrum);


